package com.sky.service.impl;

import com.sky.entity.Dish;
import com.sky.entity.Orders;
import com.sky.mapper.DishMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author majun
 * @package sky-take-out
 * @date 2024/6/5 : 下午9:13
 */

@Slf4j
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计接口
     *
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {

        //当前集合存储从begin到end所有日期
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);

        while (!begin.equals(end)) {
            //计算指定日期的后一天
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Double> turnoverList = new ArrayList<>();

        for (LocalDate date : dateList) {

            //营业额 状态为已完成的订单金额总计
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap<>();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            map.put("status", Orders.COMPLETED);

            Double turnover = orderMapper.sumByMap(map);

            //如果turnover为空则返回0.0
            turnover = turnover == null ? 0.0 : turnover;

            turnoverList.add(turnover);

        }

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();

    }

    /**
     * 用户统计接口
     *
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {

        //当前集合存储从begin到end所有日期
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);

        while (!begin.equals(end)) {
            //计算指定日期的后一天
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Double> newUserList = new ArrayList<>();
        List<Double> totalUserList = new ArrayList<>();

        for (LocalDate date : dateList) {

            //营业额 状态为已完成的订单金额总计
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap<>();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);

            Double turnover = userMapper.sumByMap(map);

            Double sumUser = userMapper.sum();

            //如果turnover为空则返回0.0
            turnover = turnover == null ? 0.0 : turnover;

            newUserList.add(turnover);
            totalUserList.add(sumUser);

        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();

    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {

        //当前集合存储从begin到end所有日期
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);

        while (!begin.equals(end)) {
            //计算指定日期的后一天
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //存储订单总数
        List<Integer> orderCountList = new ArrayList<>();
        //存储每天有效订单数
        List<Integer> validOrderCountList = new ArrayList<>();

        //遍历dateList集合，查询每天有效订单数和订单总数
        for (LocalDate date : dateList) {
            //查询订单总数
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Integer ordersCount = getOrdersCount(beginTime, endTime, null);

            //查询每天有效订单数
            Integer validCount = getOrdersCount(beginTime, endTime, Orders.COMPLETED);

            orderCountList.add(ordersCount);
            validOrderCountList.add(validCount);

        }

        //计算时间内的订单总数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();

        //计算时间内有效订单数量
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        Double orderCompletionRate = 0.0;

        if (totalOrderCount != 0) {
            //计算订单完成率
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();

    }

    /**
     * 查询销量排名top10
     *
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {


        //获取前销量10的菜品
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        Map map = new HashMap<>();
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        map.put("status", Orders.COMPLETED);

        List<Orders> ordersList = orderMapper.getFromByMap(map);

        List<Long> idList = new ArrayList<>();

        for (Orders orders : ordersList) {

            Long id = orders.getId();

            idList.add(id);

        }

        List<String> nameList = new ArrayList<>();
        List<String> numberList = new ArrayList<>();

        List<HashMap> Top10List = orderDetailMapper.getTop10(idList);

        for (HashMap getTop10Dto : Top10List) {

            Dish dish = dishMapper.getById((Long) getTop10Dto.get("dish_id"));

            nameList.add(dish.getName());

            numberList.add(getTop10Dto.get("dishNumber").toString());

        }

        log.info("top10List: {}", Top10List);

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();

    }

    /**
     * 导出Excel报表接口
     *
     * @param response
     */
    public void exportBusinesData(HttpServletResponse response) {

        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        //查询数据库获取营业数据--最近30天

        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.businessDatas(dateBegin, dateEnd);

        //通过POI将数据写入excel文件中
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模版文件创建新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(resourceAsStream);

            //填充数据--时间
            XSSFSheet sheet1 = excel.getSheet("Sheet1");

            sheet1.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + " 至 " + dateEnd);

            //获得第四行
            XSSFRow row = sheet1.getRow(3);
            //填充营业额数据
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            //填充订单完成率
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            //填充新增用户数
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获得第5行
            row = sheet1.getRow(4);
            //填充有效订单
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            //平均客单价
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //TODO 详细数据填充有问题

            //填充明细数据
            int a = 0; // 将a的初始化放在for循环外部
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(1);
                BusinessDataVO businessData = workspaceService.businessData(date.toString());
                if (businessData.getNewUsers() != 0.0 || businessData.getValidOrderCount() != 0.0) {
                    //获取某一行
                    row = sheet1.getRow(8 + a);
                    row.getCell(1).setCellValue(date.toString());
                    row.getCell(2).setCellValue(businessData.getTurnover());
                    row.getCell(3).setCellValue(businessData.getValidOrderCount());
                    row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                    row.getCell(5).setCellValue(businessData.getUnitPrice());
                    row.getCell(6).setCellValue(businessData.getNewUsers());
                    a = a + 1; // 更新a的值
                }
            }


            //通过输出流将excel下载到客户浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);


            //关闭资源
            outputStream.close();
            excel.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 根据条件统计订单数量
     *
     * @param begin
     * @param end
     * @param status
     * @return
     */
    private Integer getOrdersCount(LocalDateTime begin, LocalDateTime end, Integer status) {

        Map map = new HashMap<>();
        map.put("beginTime", begin);
        map.put("endTime", end);
        map.put("status", status);

        return orderMapper.countByMap(map);

    }

}
